<template>
    <div class="main-content">
        <!-- 表格工具栏 -->
        <div class="table-toolbar">
            <el-input v-model="searchParams.keyword" placeholder="请输入来源编号/名称" size="mini" style="width: 220px; margin-right: 10px">
            </el-input>
            <el-button type="primary" size="mini" v-authCode.show="showAuthBtn('search')" @click="handleBtn('search')">查询</el-button>
            <el-button type="primary" size="mini" v-authCode.show="showAuthBtn('preview-search')" @click="handleBtn('preview-search')"
                >预览查询</el-button
            >
            <el-button type="primary" size="mini" v-authCode.show="showAuthBtn('export')" @click="handleBtn('export')">来源导出</el-button>
            <el-checkbox v-model="searchParams.showEffectSource" @change="handleBtn('showEffectSource')" style="margin-left: 10px"
                >只展示生效状态的来源</el-checkbox
            >
            <el-button type="primary" size="mini" v-authCode.show="showAuthBtn('layout')" @click="layoutDialog = true" class="right-box"
                >布局设置</el-button
            >
            <el-button type="primary" size="mini" @click="handleBtn('refresh')" class="right-box">
                <i class="el-icon-refresh-right"></i> 重新取数</el-button
            >
        </div>
        <RiskTableP
            ref="risk-table"
            :tableData="tableData"
            :tableConfig="tableConfig"
            :column="showColumns"
            :paging="paging"
            v-loading="tableLoading"
            minWidth="120px"
            class="table"
            :key="tableKey"
            :searchParams="searchParams"
            @page-change="pageChange"
        >
            <template #operation="{ row }">
                <RiskIconButton
                    type="primary"
                    icon="el-icon-view"
                    topTitle="查看来源"
                    size="mini"
                    v-authCode="showAuthBtn('row-look')"
                    @on-click="handleRowData('look', row)"
                ></RiskIconButton>
                <RiskIconButton
                    type="primary"
                    icon="el-icon-edit"
                    topTitle="编辑来源"
                    size="mini"
                    v-authCode="showAuthBtn('row-edit')"
                    @on-click="handleRowData('edit', row)"
                ></RiskIconButton>
                <RiskIconButton
                    type="primary"
                    icon="el-icon-printer"
                    topTitle="操作记录"
                    size="mini"
                    v-authCode="showAuthBtn('row-record')"
                    @on-click="handleRowData('record', row)"
                ></RiskIconButton>
            </template>
        </RiskTableP>

        <!-- 查询 -->
        <!-- <yh-dialog title="预览查询" :visible.sync="officeVisible" drag :close-on-click-modal="false" :close-on-press-escape="false">
            <div slot="footer">
                
                <el-button @click="officeVisible = false">取 消</el-button>
                <el-button type="primary" @click="searchDialogBtn('confirm')">确 认</el-button>
            </div>
        </yh-dialog> -->
        <SourceOffice v-if="officeVisible" :visible.sync="officeVisible" :details="checkedRows" />

        <!-- 查看、编辑 -->
        <el-dialog
            :title="currentRow.showDialogTitle"
            :visible.sync="basicInfoVisible"
            width="60%"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
        >
            <SourceManageInfo :info="currentRow" ref="basic-info" v-if="basicInfoVisible" />
            <div slot="footer" class="dialog-footer">
                <el-button @click="BasicDialogBtn('cancel')">取 消</el-button>
                <el-button type="primary" @click="BasicDialogBtn('confirm')" v-if="currentRow.operationType == 'edit'">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 操作记录 -->
        <el-dialog
            :title="`操作记录(${currentRow.sourceCode_})`"
            :visible.sync="recordVisible"
            width="80%"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            class="record"
        >
            <SourceManageRecord :info="currentRow" v-if="recordVisible" />
            <div slot="footer" class="dialog-footer">
                <el-button @click="recordVisible = false">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 布局设置 -->
        <RiskTableLayout
            ref="risk-table-layout"
            :tableName="'SOURCE_MANAGE_TEST'"
            :visible.sync="layoutDialog"
            :column="columns"
            :fixedColumns="fixedColumns"
        />

        <!-- 导出 -->
        <el-dialog title="导出" :visible.sync="exportVisible" width="30%" :close-on-click-modal="false" :close-on-press-escape="false">
            文件名：<el-input v-model="exportName" size="mini"></el-input>
            <div slot="footer" class="dialog-footer">
                <el-button @click="exportVisible = false">取 消</el-button>
                <el-button type="primary" @click="exportDialogBtn()">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import RiskTableP from '@/common/components/risk-table-plus.vue';
import { ColumnVO, PageVO, TableConfigVO, VueObject } from '@/common/vo';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { sourceManageReqVO } from '../../vo';
import API from '../../api/index';
import RiskTableLayout from '@/common/components/risk-table-layout-plus.vue';
import Dict from '../../dict/index';
import DictionConstUtil from '@/utils/diction-const-util';
import SourceManageInfo from './source-manage-info.vue';
import SourceManageRecord from './source-manage-record.vue';
import SourceOffice from './source-office.vue';
@Component({ name: 'SourceManage', components: { RiskTableP, RiskIconButton, RiskTableLayout, SourceManageInfo, SourceManageRecord, SourceOffice } })
export default class SourceManage extends Vue {
    Dict = new Dict();
    tableConfig: TableConfigVO = {
        rowKey: 'sourceCode_', // 主键key
        allRowKeys: [], // 所有页数据的key集合
    };
    // sourceManageDTO
    tableData: any[] = [
        {
            sourceCode_: 'HGK001',
            sourceName_: 'tk1',
            sourceType_: '3',
        },
        {
            sourceCode_: '22',
            sourceName_: 'tk2',
            sourceType_: '1',
        },
    ];
    columns: ColumnVO[] = [
        {
            type: 'checkbox',
            selectedAll: false,
            fixed: 'left',
            align: 'center',
            width: 60,
        },
        {
            field: 'sourceType_',
            title: '来源类型',
            minWidth: '140px',
            sortable: true,
            filterType: 'funnel',
            filters: [],
        },
        {
            field: 'sourceGroupType_',
            title: '来源分组',
            minWidth: '140px',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],
        },
        {
            field: 'sourceCode_',
            title: '来源编号',
            minWidth: '140px',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],
        },
        {
            field: 'sourceName_',
            title: '来源名称',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],
        },
        {
            field: 'sourceVersion_',
            title: '来源版本号',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],
        },
        {
            field: 'sourceSuitableFund_',
            title: '来源适用产品',
            minWidth: '160px',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],
        },
        {
            field: 'sourceFile_',
            title: '来源附件',
            minWidth: '180px',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],
        },
        {
            field: 'sourceStatus_',
            title: '来源状态',
            sortable: true,
            filterType: 'funnel',
            filters: DictionConstUtil.PojoToList3(this.Dict.sourceStatusPojo),
            render: value => this.Dict.sourceStatusPojo[value],
            style: value => {
                return {
                    color: {
                        '0': 'red',
                        '1': 'green',
                    }[value],
                };
            },
        },
        {
            field: 'sourcePublishDate_',
            title: '来源发布/签署日期',
            minWidth: '180px',
            sortable: true,
        },
        {
            field: 'sourceEffecDate_',
            title: '来源生效日期',
            minWidth: '160px',
            sortable: true,
        },
        {
            field: 'sourceRemark_',
            title: '来源备注',
            minWidth: '160px',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],
        },

        {
            field: 'creator_',
            title: '来源创建人',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],
        },
        {
            field: 'creatDate_',
            title: '来源创建时间',
            sortable: true,
        },
        {
            field: 'modifier_',
            title: '来源更新人',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],
        },
        {
            field: 'moduifyDate_',
            title: '来源更新时间',
            sortable: true,
        },
        {
            field: 'operation',
            title: '操作',
            fixed: 'right',
            width: 160,
            align: 'center',
            notShowTooltip: true,
        },
    ];
    fixedColumns: ColumnVO[] = [
        {
            field: 'sourceCode_',
            title: '来源编号',
            minWidth: '140px',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],
        },
    ];
    tableKey: number = -1;
    showColumns: ColumnVO[] = [];
    searchParams: sourceManageReqVO = {
        keyword: '',
        sourceType_: '',
        sourceGroupType_: '',
        sourceCode_: '',
        sourceName_: '',
        sourceVisible_: '',
        sourceSuitableFund_: '',
        sourceFile_: '',
        sourceStatus_: '',
        sourcePublishDate_: '',
        sourceEffecDate_: '',
        sourceRemark_: '',
        creator_: '',
        creatDate_: '',
        modifier_: '',
        moduifyDate_: '',
        showEffectSource: true,
    };
    // 重置请求参数模板(切换节点清除查询参数时用)
    clearParamsModel: sourceManageReqVO = {
        keyword: '',
        sourceType_: '',
        sourceGroupType_: '',
        sourceCode_: '',
        sourceName_: '',
        sourceVisible_: '',
        sourceSuitableFund_: '',
        sourceFile_: '',
        sourceStatus_: '',
        sourcePublishDate_: '',
        sourceEffecDate_: '',
        sourceRemark_: '',
        creator_: '',
        creatDate_: '',
        modifier_: '',
        moduifyDate_: '',
        showEffectSource: true,
    };

    paging: PageVO = { currentPage: 1, pageSize: 25, total: 0 };

    tableLoading: boolean = false;

    currentRow: any = {};
    officeVisible: boolean = false; // 查询框
    exportVisible: boolean = false;
    basicInfoVisible: boolean = false; // look|edit卡基本信息
    layoutDialog: boolean = false;
    recordVisible: boolean = false;
    exportName: string = ''; // 导出文件名

    @Prop() treeNodeData: any;
    /**
     * 左侧树节点的改变
     * 处理内容：查询条件重置（筛选条件）
     */
    @Watch('treeNodeData', { deep: true })
    changeNode() {
        this.$nextTick(() => {
            const $Table = this.$refs['risk-table'] as any;
            const $xTable = $Table?.$refs['xTable'];
            ($xTable as any).clearFilter();
            this.searchParams = JSON.parse(JSON.stringify(this.clearParamsModel));
            // treeNodeData中的字段对应查询参数中的哪些 TODO
            this.getTableData();
        });
    }

    mounted() {
        // 监听布局设置
        this.$watch(
            () => {
                return (this.$refs['risk-table-layout'] as VueObject).showColumns;
            },
            val => {
                this.showColumns = val && val.length ? val : this.columns;
                this.tableKey++;
            }
        );
        this.getTableData();
    }
    /**
     * 获取表格列表
     */
    getTableData() {
        this.tableLoading = true;
        API.sourceManageList({ ...this.searchParams, paging: this.paging })
            .then((res: any) => {
                this.tableData = res.list;
                this.paging.total = res.total;
            })
            .finally(() => {
                this.tableLoading = false;
            });
    }
    /**
     * 分页、排序、筛选等
     */
    pageChange() {
        this.getTableData();
    }
    /**
     * @operation 操作类型 search|refresh|export|showEffective_
     * @row 行数据
     */
    async handleBtn(operation: string): Promise<void> {
        console.log('预览查询|导入|导出|复选框改变:', operation);
        if (operation == 'search' || operation == 'refresh') {
            this.paging.currentPage = 1;
            this.getTableData();
        } else if (operation === 'preview-search') {
            this.officeVisible = true;
        } else if (operation === 'export') {
            // 导出时需要填写导出名称
            this.exportVisible = true;
        } else if (['showEffectSource'].includes(operation)) {
            this.paging.currentPage = 1;
            this.getTableData();
        }
    }

    /**
     * 操作行 type:look|edit|record
     */
    handleRowData(type: string, row: any) {
        console.log('操作行:', type, row);
        this.currentRow = JSON.parse(JSON.stringify(row));
        this.currentRow.operationType = type;
        if (type == 'look') {
            this.currentRow.showDialogTitle = `查看来源(${this.currentRow.sourceCode_})`;
            this.basicInfoVisible = true;
        } else if (type == 'edit') {
            this.currentRow.showDialogTitle = `编辑来源(${this.currentRow.sourceCode_})`;
            this.basicInfoVisible = true;
        } else if (type == 'record') {
            this.recordVisible = true;
        }
    }

    /**
     * 查询弹框按钮处理
     */
    searchDialogBtn(type: string) {}

    /**
     * 查看、编辑
     */
    BasicDialogBtn(type: string) {
        if (type == 'cancel') {
            this.basicInfoVisible = false;
        } else if (type == 'confirm') {
            // 查看无需处理，编辑请求接口
            let info = (this.$refs['basic-info'] as any).basicForm;
            API.editSourceManage(info)
                .then((res: any) => {
                    this.yh_message_success('编辑成功!');
                })
                .catch(() => {})
                .finally(() => {
                    this.basicInfoVisible = false;
                });
        }
    }

    /**
     * 导出确认
     */
    async exportDialogBtn() {
        let checkRowKeys = (this.$refs['risk-table'] as any).checkRowKeys || [];
        await API.downLoadFileSourceManage({ ...this.searchParams, checkRowKeys, exportName: this.exportName });
        this.exportVisible = false;
    }

    /**
     * 按钮权限设置
     */
    showAuthBtn(type: string) {
        let obj = {
            search: '',
            'preview-search': '',
            export: '',
            layout: '',
            'row-look': '',
            'row-record': '',
            'row-edit': '',
        };
        return 'B_0016';
        // return obj[type];
    }
}
</script>
<style lang="scss" scoped>
.main-content {
    height: 100%;
    .table-toolbar {
        padding: 12px;
        .item {
            margin-left: 10px;
        }
        .right-box {
            float: right;
            margin-left: 10px;
        }
    }
    .table {
        height: calc(100% - 60px) !important;
    }
}

.vxe-input.size--mini {
    height: 26px;
    line-height: 36px;
}
/deep/ .el-textarea .el-textarea__inner {
    resize: none;
}

.record /deep/ .el-dialog .el-dialog__body {
    max-height: none;
}
</style>
